package com.uenpay.im.ui.old.activity.oa;

import com.qiyunxin.android.http.net.HttpInvokeItem;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.HttpInvokeResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 获取oa列表
 * 
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */
public class GetOaInvokeItem extends HttpInvokeItem {
	public class GetOaInvokeItemResult extends HttpInvokeResult {
		public ArrayList<AppGroupEntity> arrayList = new ArrayList<AppGroupEntity>();
	}

	public GetOaInvokeItemResult getOutput() {
		return (GetOaInvokeItemResult) GetResultObject();
	}

	public GetOaInvokeItem(int entid) {
		String url = APIConfiguration.getBaseUrl()
				+ "Oa/Application/myApplications?entid=" + entid + "&"
				+ APIConfiguration.getCustIdAndToken();
		SetUrl(url);
	}

	@Override
	protected Object DeserializeResult(String responseBody) {
		GetOaInvokeItemResult result = new GetOaInvokeItemResult();
		try {
			JSONObject json = new JSONObject(responseBody);
			result.status = json.optInt("status");
			result.msg = json.optString("msg");

			JSONArray array = json.optJSONArray("data");
			if (array != null && array.length() > 0) {
				for (int i = 0, size = array.length(); i < size; i++) {
					result.arrayList.add(desAppGroupEntity(array
							.optJSONObject(i)));
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
			return result;
		}

		return result;
	}

	private AppGroupEntity desAppGroupEntity(JSONObject json) {
		AppGroupEntity appGroupEntity = new AppGroupEntity();
		appGroupEntity.groupid = json.optInt("groupid");
		appGroupEntity.groupname = json.optString("groupname");
		if (json.has("app")) {
			JSONArray array = json.optJSONArray("app");
			if (array != null && array.length() > 0) {
				for (int i = 0, size = array.length(); i < size; i++) {
					appGroupEntity.arrayList.add(desAppEntity(array
							.optJSONObject(i)));
				}
			}
		}
		return appGroupEntity;
	}

	private AppEntity desAppEntity(JSONObject json) {
		AppEntity mAppEntity = new AppEntity();
		mAppEntity.logo = json.optString("logo");
		mAppEntity.url = json.optString("url");
		mAppEntity.title = json.optString("title");
		mAppEntity.type = json.optInt("type");
		return mAppEntity;
	}
}
